/**
 * 防抖函数
 * @param {Function} func 要执行的函数
 * @param {number} wait 延迟时间（毫秒）
 * @param {boolean} immediate 是否立即执行
 * @returns {Function} 防抖处理后的函数
 */
export function debounce(func, wait = 300, immediate = false) {
  let timeout
  
  return function(...args) {
    const context = this
    const later = function() {
      timeout = null
      if (!immediate) func.apply(context, args)
    }
    
    const callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    
    if (callNow) func.apply(context, args)
  }
}

/**
 * 节流函数
 * @param {Function} func 要执行的函数
 * @param {number} wait 延迟时间（毫秒）
 * @returns {Function} 节流处理后的函数
 */
export function throttle(func, wait = 300) {
  let timeout = null
  let previous = 0
  
  return function(...args) {
    const context = this
    const now = Date.now()
    
    const remaining = wait - (now - previous)
    
    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout(timeout)
        timeout = null
      }
      
      previous = now
      func.apply(context, args)
    } else if (!timeout) {
      timeout = setTimeout(() => {
        previous = Date.now()
        timeout = null
        func.apply(context, args)
      }, remaining)
    }
  }
}

/**
 * 格式化日期
 * @param {Date|string|number} date 日期对象、日期字符串或时间戳
 * @param {string} format 格式字符串，如 'YYYY-MM-DD HH:mm:ss'
 * @returns {string} 格式化后的日期字符串
 */
export function formatDate(date, format = 'YYYY-MM-DD') {
  if (!date) return ''
  
  const d = new Date(date)
  
  if (isNaN(d.getTime())) return ''
  
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

/**
 * 将对象转换为查询字符串
 * @param {Object} params 参数对象
 * @returns {string} 查询字符串（不包含?前缀）
 */
export function objectToQueryString(params) {
  if (!params || typeof params !== 'object') return ''
  
  return Object.keys(params)
    .filter(key => params[key] != null && params[key] !== '')
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&')
}

/**
 * 从查询字符串解析参数
 * @param {string} queryString 查询字符串（可包含?前缀）
 * @returns {Object} 参数对象
 */
export function queryStringToObject(queryString) {
  if (!queryString) return {}
  
  const queryStr = queryString.startsWith('?') 
    ? queryString.substring(1) 
    : queryString
  
  if (!queryStr) return {}
  
  const result = {}
  
  queryStr.split('&').forEach(part => {
    const [key, value] = part.split('=')
    if (key) {
      result[decodeURIComponent(key)] = value ? decodeURIComponent(value) : ''
    }
  })
  
  return result
}